// pages/settlement/settlement.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    haveAddress: false,
    addresInfo:{},
    inPay: true,
    couponList:[],
    expressList: [{
      pi_name:"请选择其他快递"
    }],
    showModalStatus:false,
    animationData:{},
    userMessages:'',
    selectExpressToggle:false,
    selecticonExpress:0,
    postageMoney:0.00,
    totalPrice:0.00
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    wx.request({
      url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/orderIndex/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
      method: "get",
      data: {
        customerid: wx.getStorageSync("customerid"),
        share_id: wx.getStorageSync("share_id"),
        vip_id: wx.getStorageSync("vip_id")
      },
      success: function (res) {
        console.log(res)
        let expressList = that.data.expressList.concat(res.data.data.express_list.datas)
        that.setData({
          expressList,
          couponList: res.data.data.coupon_list,
          totalPrice: res.data.data.total_price
        })
        
      }
    })
  },
  address: function (e) {
    var that = this
    wx.request({
      url: "https://api.hepulanerp.com/hpl/index.php?s=/Api/hfzx/index",
      method: 'POST',
      data: {
        key: 'be15d4ca913c91494cb4f9cd6ce317c6',
        type: "get-address-list",
        data: {
          'vip_id': wx.getStorageSync('vip_id'),
          'origin': 'hplgwsc',
          'mobile': wx.getStorageSync('mobile'),
        }
      },
      success: function (res) {
        that.setData({
          address_list: res.data.data,
          showModalStatus: true,
          selectExpressToggle:false
        })
      }
    })
  },
  setAddress: function(e) {
    let value = e.currentTarget.dataset.info;
    let that = this;
    that.setData({
      haveAddress: true,
      showModalStatus:false,
      addresInfo: value
    })
    wx.request({
      url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/getExpressList/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
      method: 'get',
      data: {
        prov_id: that.data.addresInfo.prov,
        city_id: that.data.addresInfo.city
      },
      success: function (res) {
        let expressList = [{
          pi_name: "请选择其他快递"
        }].concat(res.data.datas)
        that.setData({
          selecticonExpress:0,
          expressList
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    if (that.data.showModalStatus){
      that.address();
    }
  },
  writeMessages(e){
    this.setData({
      userMessages: e.detail.value
    })
  },
  wxplay(e) {
    var that = this
    if (that.data.haveAddress == false) {
      wx.showModal({
        title: '温馨提示',
        content: '请填写或选择收货地址',
        showCancel: false,
      })
      return false;
    }
    if (that.data.selecticonExpress == 0) {
      wx.showModal({
        title: '温馨提示',
        content: '请选择配送方式',
        showCancel: false,
      })
      return false;
    }

    if (that.data.inPay == true) {
      that.setData({
        inPay: false
      })
      if (wx.getStorageSync('customerid') == 0 || wx.getStorageSync('customerid') == null) {
        wx.request({
          url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/is_customerid/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
          method: 'POST',
         
          success: (res) => {
            if (res.data.vip_id != 0 && res.data.vip_id != '') {
              wx.setStorageSync('vip_id', res.data.vip_id);
            }
            wx.setStorageSync('customerid', res.data.customerid);
          }
        })
      }
      // //如果未选择收货快递，则改为默认的快递
      // let expressid = that.data.expressList[that.data.selecticonExpress].pi_num
      // if (expressid == 0) {
      //   expressid = 6
      // }
      let coupon_id = 0;
      //如果选择顺丰快递，判断该用户是否在配送地区内
      if (that.data.couponList.data.length > 0){
        coupon_id = that.data.couponList.data[0].id
      }
      wx.request({
        url: app.urlData.getURL + '/index.php/weshop/SApi/index/key/' + app.urlData.key + '/m/saveOrder/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
        method: 'POST',
        data: {
          share_id: wx.getStorageSync('share_id'),
          message: that.data.userMessages,
          reserve_type:0,
          address: that.data.addresInfo.address + that.data.addresInfo.detail,
          contact: that.data.addresInfo.contact,
          phone: that.data.addresInfo.mobile,
          addressid: that.data.addresInfo.addressid,
          customerid: wx.getStorageSync('customerid'),
          vip_id: wx.getStorageSync('vip_id'),
          expressid: that.data.expressList[that.data.selecticonExpress].pi_num, //已选择的快递
          prov: that.data.addresInfo.prov,
          city: that.data.addresInfo.city,
          coupon_id: coupon_id,
        },
        header: {
          "content-type": 'application/x-www-form-urlencoded'
        },
        success: (res) => {
          console.log(res.data.datas)
          if (res.data.status == 1) {
            wx.requestPayment({
              'appId': res.data.datas.appId,
              'nonceStr': res.data.datas.nonceStr,
              'package': res.data.datas.package,
              'signType': res.data.datas.signType,
              'paySign': res.data.datas.paySign,
              'timeStamp': res.data.datas.timeStamp,
              'success': function(res) {
                wx.showModal({
                  title: '恭喜您',
                  showCancel: false,
                  content: '已成功购买，请在系统消息中查看！',
                  success: function(res) {
                    console.log(res)
                    //这里写支付成功后操作
                    wx.redirectTo({
                      url: '../userOrder/userOrder',
                    })
                  }
                })
              }, 
              fail:(res) =>{
                wx.navigateTo({
                  url: '../userOrder/userOrder',
                })
              }
            })
          } else {
            wx.showModal({
              title: '温馨提示',
              content: res.data.msg,
              showCancel: false,
              success: function(res) {
                if(res.confirm){
                  wx.navigateBack();
                }
              }
            })
          }
        },
      })
      that.setData({
        inPay: true
      })
      
    }
  },
  util: function (e) {
    var currentStatu = e.currentTarget.dataset.statu
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 300, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画
    animation.translateY(500).step()

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })

      //关闭
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false,
        });
      }
    }.bind(this), 200)

    // 显示
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true,
      });
    }
  },
  close: function (e) {
    var that = this
    that.util(e)
  },
  addAddre: function () {
    wx.navigateTo({
      url: '/pages/newaddress/newaddress',
    })
  },
  //收集formId
  formSubmit: function(e) {
    var formId = e.detail.formId
    var that = this
    if (formId) {
      wx.request({
        url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/add_formid/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
        method: 'get',
        data: {
          type: 2,
          form_id: formId,
          user_id: wx.getStorageSync('ydn_id'),
        },
        success: (res) => {

        }
      })
    }
  },
  toggleDelivery:function(){
    let that = this;
    if (that.data.selectExpressToggle) {
      that.setData({
        selectExpressToggle: false
      })
    } else{
      that.setData({
        selectExpressToggle: true
      })
    }
  },
  changExpress: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    
    if (that.data.expressList[index].pi_num == 1) {
      that.setData({
        selectExpressToggle: false,
        postageMoney: 18.00,
        selecticonExpress: index
      })
    } else{
      that.setData({
        selectExpressToggle:false,
        postageMoney: 0.00,
        selecticonExpress: index
      })
    }
  },
})
